//对后台管理的路由监听的入口文件
const express = require("express");
const router = express.Router();
const linkTable = require("../../../database/link")
const { URL } = require("url");



router.post("/addData", async (req, res) => {
    // console.log(new URL(req.body.linkUrl));
    let { origin } = new URL(req.body.linkUrl)

    //根据正则匹配查询home字段值里有没有同一个网站的友链
    let linkDoc = await linkTable.findOne({ linkUrl: new RegExp(origin) });
    if (linkDoc) return res.send({ code: 10, message: "请不要重复添加相同网站下的友链！" });

    await linkTable.create(req.body);
    res.send({ code: 0, message: "添加友链成功", data: req.body });

});

router.post("/update", async (req, res) => {

    let { _id, name, linkUrl, imgUrl, desc } = req.body;

    //数据校验： 友链id是否存在  
    let linkDoc = await linkTable.findById(_id);
    if (!linkDoc) return res.send({ code: 1, message: "你要修改的这条友链不存在，请检查！" });

    await linkTable.findByIdAndUpdate(_id, { name, linkUrl, imgUrl, desc }); //到数据表中修改数据
    res.send({ code: 0, message: "友链修改成功" });

});

router.post("/delete", async (req, res) => {
    let { _id } = req.body

    let linkDoc = await linkTable.findById(_id)
    if (!linkDoc) return res.send({ code: 1, message: "你要修改的这条友链不存在，请检查！" });

    await linkTable.findByIdAndDelete(_id); //根据id删除数据

    res.send({ code: 0, message: "友链删除成功" });


})

module.exports = router;


